package cn.ym.mall.dao.impl;

import cn.ym.mall.dao.BrandDao;
import cn.ym.mall.entity.ActiveType;
import cn.ym.mall.entity.Brand;
import cn.ym.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 漆家乐
 */
public class BrandDaoImpl implements BrandDao {
    QueryRunner queryRunner = new QueryRunner();
    /**
     * 查询所有品牌
     *
     * @return
     */
    @Override
    public List<Brand> getAll() throws SQLException {
        List<Brand> brandsList = new ArrayList<Brand>();
        try{
            String sql = "select * from brand;";
            brandsList = queryRunner.query(DruidUtils.getConnection(),sql,new BeanListHandler<Brand>(Brand.class));
        }catch (Exception e){
            e.printStackTrace();
        }
        return brandsList;
    }

    /**
     * 根据id查询品牌
     *
     * @param bid
     * @return
     */
    @Override
    public Brand getBrandByBid(Integer bid) throws SQLException {
        Brand brand = null;
        try{
            String sql = "select * from brand where bid = '?';";
            brand = queryRunner.query(sql,new BeanHandler<Brand>(Brand.class),bid);
        }catch (Exception e){
            e.printStackTrace();
        }
        return brand;
    }

    /**
     * 添加品牌
     *
     * @param brand
     * @return
     */
    @Override
    public int add(Brand brand) throws SQLException {
        int num = 0;
        try{
            String sql = "insert into brand(bid,bname) value(?,?);";
            num = queryRunner.update(DruidUtils.getConnection(),sql,brand);
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }

    /**
     * 修改品牌
     *
     * @param brand
     * @return
     */
    @Override
    public int update(Brand brand) throws SQLException {
        int num = 0;
        try{
            String sql = "update brand set bname=? where bid=?;";
            num = queryRunner.update(DruidUtils.getConnection(),sql,brand);
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }

    /**
     * 删除品牌
     *
     * @param bid
     * @return
     */
    @Override
    public int delete(Integer bid) throws SQLException {
        int num = 0;
        try{
            String sql = "delete from brand where bid='?';";
            num = queryRunner.update(DruidUtils.getConnection(),sql,bid);
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }
}
